package oktx.config;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * Created by dave on 18-5-19 下午12:39.
 */
public class ApplicationContextHolder implements ApplicationContextAware {
    private static ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }

    public static ApplicationContext get() {
        return context;
    }

    public static <T> T getBean(Class<T> clazz) {
        if (context == null) {
            return null;
        }
        try {
            return context.getBean(clazz);
        } catch (BeansException e) {
            return null;
        }
    }

    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) {
        if (context == null) {
            return null;
        }
        try {
            return (T) context.getBean(name);
        } catch (BeansException e) {
            return null;
        }
    }
}
